//
//  TakePhotoController.m
//  ZZmetro
//
//  Created by 一介布衣 on 2020/6/16.
//  Copyright © 2020 一介布衣. All rights reserved.
//

#import "TakePhotoController.h"
#import "UIViewController+App.h"
#import "ImageCompressTool.h"

@interface TakePhotoController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@end

@implementation TakePhotoController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
}

-(void) viewDidLoad{
    [super viewDidLoad];
    if (self.pickType == 1) {
        [self pickPhoto];
    } else if (self.pickType == 2) {
        [self takePhoto];
    } else {
        [self openPhotoChoiceDialog];
    }
    [self takePhoto];
}


- (void) openPhotoChoiceDialog {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *selectPhotoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickPhoto];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:takePhotoAction];
    [alertController addAction:selectPhotoAction];
    if (alertController) {
        [alertController setModalPresentationStyle:UIModalPresentationPopover];
        
        UIPopoverPresentationController *popPresenter = [alertController
                                                         popoverPresentationController];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

//获取照片从相册
-(void)pickPhoto{
    UIImagePickerController *imagePickerController =[[UIImagePickerController alloc] init];
    imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

-(void) takePhoto {
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController* picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:NO completion:nil];
    }else {
        [Toast toast:@"相机不可用"];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *edtImage = info[UIImagePickerControllerEditedImage];
    UIImage *srcImage = info[UIImagePickerControllerOriginalImage];
    
    //保存原图
    NSString* fileNme = [FileHandler cacheFile:@"src.jpeg"];
    NSData *srcImgData = UIImageJPEGRepresentation(srcImage, 1);
    [srcImgData writeToFile:fileNme atomically:YES];
    
    //压缩
    [self compressImg:srcImage];
    
    [Toast toast:@"获取图片成功"];
    NSLog(@"=========pick img===========");
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
}

//按取消按钮时候的功能
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"=========pick img cancel===========");
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
}

-(void) compressImg:(UIImage*) img {
    //UIImage *img = [UIImage imageNamed:@"be_welcome.jpeg"];
    CGSize size = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    [ImageCompressTool CompressToDataAtBackgroundWithImage:img
                                                    ShowSize:size
                                                    FileSize:100
                                                       block:^(NSData *resultData) {
        UIImage *newIMG = [UIImage imageWithData:resultData];
        NSData *newIMGData = UIImageJPEGRepresentation(newIMG,1);
        
        NSString* fileNme = [FileHandler cacheFile:@"test.jpeg"];
        BOOL succ = [resultData writeToFile:fileNme atomically:YES];
        //NSString* s = (succ == YES) ? @"True" : @"False";
        //NSLog(fileNme);
        //NSLog(s);
        
        //获取主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            //NSString *info = [NSString stringWithFormat:@"压缩得到的NSData大小：%lu kb\n\n使用Data再次创建的UIImage的大小： %lu kb",[resultData length]/1024,[newIMGData length]/1024];
            //[Toast toast:info];
            
            if (self.photoTokenBlcok) {
                self.photoTokenBlcok(newIMG, succ ? fileNme : nil);
            }
        });
        
        
    }];
}

@end
